package cn.zz.veggie.web.types.dto.mgmt.order;

import java.util.List;
import java.util.Optional;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonIgnore;

import cn.hutool.core.util.StrUtil;
import cn.zz.comm.exception.classes.ParamInvalidException;
import cn.zz.comm.util.CollectorUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Getter;
import lombok.Setter;

/**
 * @author zhongq
 * @since 2024/6/1
 */
@Getter
@Setter
public class MgmtOrderCreateDto {
	@NotNull
	@Positive
	private Integer shopId;
	private String remark;
	@NotNull
	private Long deliveryTime;
	@NotNull
	@NotEmpty
	private List<@Valid MgmtOrderItemDto> items;

	// ignore
	@JsonIgnore
	private Integer amount;

	public void requireValid(Set<Integer> pids) {
		Optional<MgmtOrderItemDto> item = items.stream().filter(e -> !pids.contains(e.getProductId())).findAny();
		if (item.isPresent()) {
			throw new ParamInvalidException("product not found " + item.get().getProductId());
		}
		this.remark = StrUtil.nullToEmpty(remark);
		this.amount = null;
	}

	public Set<Integer> collectProductIds() {
		return CollectorUtil.bws(items, MgmtOrderItemDto::getProductId);
	}

	public Integer calcAmount() {
		if (amount == null) {
			amount = items.stream().mapToInt(MgmtOrderItemDto::calcAmount).sum();
		}
		return amount;
	}
}